package com.flyxiaozhu.rabbitmqdemo;

import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

@Component
public class RabbitMqProducer implements RabbitTemplate.ConfirmCallback, RabbitTemplate.ReturnCallback {
    @Autowired
    private RabbitTemplate rabbitTemplate;

    //需初始化设置
    @Bean
    public void createRabbitTemplate() {
        rabbitTemplate.setConfirmCallback(this);
        rabbitTemplate.setReturnCallback(this);
    }

    //确认消息是否到达Exchange b为false则发送失败
    @Override
    public void confirm(CorrelationData correlationData, boolean b, String s) {
        if (!b) {
            System.out.println("消息发送失败,失败原因:" + s);
        }
    }

    //确认消息是否到达Queue，消息发送失败触发(比如routing_key匹配不到queue)
    @Override
    public void returnedMessage(Message message, int i, String s, String s1, String s2) {
        System.out.println("进入returnCallback！exchange:" + s1 + ",routingkey:" + s2);
        System.out.println("消息内容:" + message + ",失败原因:" + s);
    }
}
